package com.ctbri.io;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.ctbri.util.OSExecuteException;

public class Ex22_OSExecute {
	public static void command(String command) {
		boolean err = false;
		try {
			Process process = new ProcessBuilder(command.split(" ")).start();
			BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String s;
			List<String> outputContents = new ArrayList<>();
			while((s = results.readLine()) != null) {
				outputContents.add(s);
			}
			
			BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			List<String> errContents = new ArrayList<>();
			while((s = errors.readLine()) != null) {
				errContents.add(s);
				err = true;
			}
			
			System.out.println(outputContents);
			System.out.println(errContents);
			
		} catch (Exception e) {
			if(!command.startsWith("CMD /C"))
				command("CMD /C " + command);
			else
				throw new RuntimeException(e);
		}

		if(err)
			throw new OSExecuteException("Errors executing " + command);
	}
	
	public static void main(String[] args) {
		command("java D:/Java/workspace/thinkinginjava/src/com/ctbri/io/OSExecuteDemo.java");
	}
}
